package com.tssm.core.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author 徐龙
 * 
 * @param <T>
 */
public class FieldValueUtil<T> {

	public List<T> setObjectList(List<T> tl, T t) throws SecurityException,
			NoSuchMethodException, IllegalAccessException,
			InvocationTargetException, InstantiationException {
		List<T> results = new ArrayList<T>();
		for (Iterator it = tl.iterator(); it.hasNext();) {

			Object obj = t.getClass().newInstance();
			T to = (T) obj;
			// 获得对象的类型
			Class<?> classType = to.getClass();
			// 获得对象的所有属性
			Field fields[] = classType.getDeclaredFields();
			Map map = (Map) it.next();
			for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) {
				Map.Entry element = (Map.Entry) iter.next();
				Object strKey = element.getKey();// 键
				Object strValue = element.getValue();// 值
				for (int i = 0; i < fields.length; i++) {
					Field field = fields[i];
					String fieldName = field.getName();
					if (fieldName.toLowerCase().equals(
							strKey.toString().toLowerCase())) {
						// 把属性名的第一个字母变成大写
						String firstLetter = fieldName.substring(0, 1)
								.toUpperCase();
						// 获得和属性对应的setXXX()方法的名字
						String setMethodName = "set" + firstLetter
								+ fieldName.substring(1);
						// 获得和属性对应的setXXX()方法

						Method setMethod = classType.getMethod(setMethodName,
								new Class[] { field.getType() });
						// 赋值方法
						setMethod.invoke(to, new Object[] { strValue });
						break;
					}
				}
			}

			results.add(to);
		}
		return results;

	}

}
